#!/usr/bin/env python
# -*- coding: utf-8 -*-

import requests, re, json, sys
from lxml import etree

class GetSiteInfo():

	SiteInfo = {	'site': '',
				'alexa':{None},
				'whois':{None},
				'baidu_rank':{None}
				}

	def __init__(self, site):
		if len(site.split('://')) == 2:
			self.site = site.split('://')[1].split('/')[0]
		else:
			self.site = site.split('/')[0]
		self.SiteInfo['site'] = self.site

	def run(self):
		self.res_world = None

		print 'Analyze site: %s' % self.site
		try:
			self.res_world = requests.get('http://www.aizhan.com/siteall/' + self.site)
		except:
			pass
		if self.res_world:
			self.SiteInfo['alexa'] = self.get_alexa()
			self.SiteInfo['whois'] = self.get_whois()
		self.SiteInfo['baidu_rank'] = self.get_baidu_rank()
		return self.SiteInfo

	def get_alexa(self):
		rank, IPPV, pr = [None] * 3
		tree = etree.HTML(self.res_world.text)
		rank = tree.xpath('//span[@id="alexa_3months"]/text()')
		if rank:
			rank = rank[0]
		IPPV = tree.xpath('//span[@id="alexa_IPPV"]/text()')
		if IPPV:
			IPPV = IPPV[0]
		pr = tree.xpath('//span[@id="main_pr"]/img')
		if pr:
			pr = pr[0].get('src').split('/')[-1][2:-4]

		return {'rank':rank, 'PR':pr, 'IPPV':IPPV} 

	def get_whois(self):
		w = re.search('set_whois\(\{.*?\}\)',self.res_world.text)
		if w:
			whois = w.group()
			return json.loads(whois[10:-1])
		else:
			return {None}

	def get_baidu_rank(self):
		self.res_baidu = None
		br, ip, date, brother = [None] * 4
		try:
			self.res_baidu = requests.get('http://baidurank.aizhan.com/baidu/' + self.site)
		except:
			pass
		if self.res_baidu:
			tree = etree.HTML(self.res_baidu.text)
			br = tree.xpath('//img[@align="absmiddle"]')
			if br:
				br =  br[0].get('src')[-5:-4]
			ip = tree.xpath('//span[@class="red"]/text()')[:3]
			date = tree.xpath('//span[@id="baidu_date"]/a/text()')
			if date:
				date = date[0]
			brother = tree.xpath('//a[@class="brothersites"]/text()')
			return {'BR': br, 'BDIP': ip[0], 'PCIP': ip[1], 'MobileIP':ip[2], 'SnapDate': date, 'BrotherSites':brother} 
		else:
			return {None}

	def get_server_info(self):
		return requests.get('http://' + self.site).headers

if __name__ == '__main__':
	#main()
	if len(sys.argv)!= 2:
		print 'usage: sys.argv[0] site_name'
		sys.exit()

	info = GetSiteInfo(sys.argv[1]).run()
	print info.SiteInfo

